import {Effect, Reducer} from 'umi';
import {queryCurrent, query as queryUsers} from '@/services/user';
import {codeCallback} from "@/services/api";
import {get} from "lodash"
import {checkCode} from "@/utils/utils";
import {getUserInfo} from "@/services/api";
import {setAuthority} from "@/utils/authority";
export interface CurrentUser {
  avatar?: string;
  name?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  userid?: string;
  unreadCount?: number;
}
export interface UserModelState {
  currentUser?: CurrentUser;
  token?: string
}
export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
    fetchToken: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
    changeToken: Reducer<UserModelState>;
  };
}
const UserModel: UserModelType = {
  namespace: 'user',
  state: {
    currentUser: {},
    token: ""
  },
  effects: {
    * fetchToken({payload}, {call, put, select}) {
      let response = yield call(codeCallback, payload);
      if (checkCode(get(response, "code", 0))) {
        let result = yield put({
          type: "changeToken",
          payload: get(response, "data", "")
        })
        Promise.resolve(result)
      } else {
        Promise.reject(response)
      }
    },
    * fetch(_, {call, put}) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    * fetchCurrent(_, {call, put}) {
      const response = yield call(getUserInfo);

      let result = yield put({
        type: 'saveCurrentUser',
        payload: get(response, "data", {}),
      });
      return Promise.resolve(result)
    },
  },
  reducers: {
    changeToken(state, action) {
      return {
        ...state,
        token: action.payload
      };
    },
    saveCurrentUser(state, action) {

      setAuthority(get(action, "payload", {}))
      return {
        ...state,
        currentUser: action.payload,
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
